package com.example.coupon.service;

import com.example.coupon.comon.enums.ActivityStatusEnum;
import com.example.coupon.controller.vo.ActivityVO;
import com.example.coupon.dao.ActivityMapper;
import com.example.coupon.dao.MerchantActivityMapper;
import com.example.coupon.entity.ActivityEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.Date;

import java.util.Map;

@Service
public class ActivityService {

    @Autowired
    private ActivityMapper activityMapper;

    @Autowired
    private CouponService couponService;

    @Autowired
    private MerchantActivityMapper merchantActivityMapper;

    //添加活动，并且将活动的优惠券创建出来
    @Transactional
    public String addActivity(ActivityVO activityVO) {
        ActivityEntity activityEntity = ActivityEntity.transferToEntity(activityVO);
        activityEntity.setStatus(ActivityStatusEnum.NOT_START.getCode());
        //1、添加活动
        activityMapper.insertActivity(activityEntity);
        if (activityEntity.getId() != null) {
            //2、把活动id拿着去添加优惠券
            Integer result = couponService.addCoupon(activityEntity.getId(), activityVO.getAmount(),
                    activityVO.getStartTime(), activityVO.getEndTime());
            if (result > 0) {
                return "活动创建成功";
            }
            throw new RuntimeException("优惠券创建失败，活动创建失败");
        }
        return "活动创建失败";
    }

    public String signUpActivity(Long merchantId, Long activityId) {
        Map<String, Object> activityMap = activityMapper.queryActivityById(activityId);
        if (activityMap.size() <= 0){
            return "活动不存在，报名失败";
        }
        Integer status = Integer.parseInt(activityMap.get("status").toString());
        if (!ActivityStatusEnum.UNDERWAY.getCode().equals(status)){
            return "活动不在进行中，报名失败";
        }
        Integer result = merchantActivityMapper.insertMerchantActivity(merchantId, activityId, new Date());
        if (result > 0) {
            return "商家报名活动成功";
        }
        return "商家报名活动失败";
    }

}